using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MindFactorial.LaunchPoint.Runtime;
using MindFactorial.LaunchPoint.Console.Library;
using MindFactorial.LaunchPoint.Common;

namespace MindFactorial.LaunchPoint.Console
{
    /// <summary>
    /// Interaction logic for ConsoleShell.xaml
    /// </summary>

    public partial class ConsoleShell : IRootWindow
    {
        
        PluginMessagingPipeline _pipeline = null;
        Dictionary<string, ConsolePlugIn> _plugins = null;
        MenuPresentationContext _menucontext = null;
        ConsolePlugIn _currentPlugin = null;
        ConsoleWindow _window = null;
        StartupApplication _startupApp = null;
        Image _large_icon;
        

        //ImageBrush _consoleHeader;

        public ConsoleShell(StartupApplication startupApp, ConsoleWindow window)
        {
            InitializeComponent();
            _startupApp = startupApp;
            this._window = window;           
            _pipeline = new PluginMessagingPipeline(this);
            _plugins = new Dictionary<string, ConsolePlugIn>();
                     

            _menucontext = new MenuPresentationContext(_menuMain);

          
           


            this.Loaded += delegate(object sender, RoutedEventArgs e)
            {
                //set the window title here
                if (this.CurrentPlugin != null)
                {
                    _window.WindowTitle = string.Format("{0} ({1} {2})", this.CurrentPlugin.Label,Properties.Resources.lblLoggedIn, _window.CurrentUser);
                    _currentPlugin.Controllers.NotifyPluginLoaded();
                }
                else
                {
                    MindFactorial.LaunchPoint.Common.Logger.Log("3C2AB0FB-D4D3-4e81-8EB8-263D1FA17637:  The plugin was never loaded." );
                    MessageBox.Show(Properties.Resources.lblPlugInUnavailable,"",MessageBoxButton.OK,MessageBoxImage.Error);
                }
            };
            

            //setup surfaces when application launch event is fired
            _surfaceControlPanel._applicationLaunching += delegate(string appname)
            {
                if (_plugins.ContainsKey(appname))
                {
                    this._window.NavigateToPlugin(appname);                    
                }
                else
                {
                    PromptManager.Alert("417A40DD-3A44-40c2-9C14-904F7A735C2E: Plugin with name {0} does not exist", appname);
                }
            };
        }

        internal void Initialize(ConsolePlugIn target)
        {
            
            //set console title
            //THERE IS NO NEED TO SET TITLE HERE SINCE IT IS SET WHEN THE ITEM IS SELECTED
            //_window.Title = target.Label;

            //give the console plugin a context to the entire window

            

            //set presentation for CONTEXT area
            _surfaceControlPanel.LaunchApplication(target);


            //set presentation for content surface
            _surfaceContentpanel.SetPresentationSurface(target.ContentAreaSurfacePresenter);
            target.ContentAreaSurfacePresenter.SetHost(_surfaceContentpanel);

            //set presentation for toolbar surface
            _surfaceToolbarPanel.SetPresentationSurface(target.ToolbarAreaSurfacePresenter);


            //delete previous plugin's menus
            if (_currentPlugin != null)
                _currentPlugin.TopLevelMenuPresenter.ClearMenuContext();

            //set main menu context manager for this plugin
            target.TopLevelMenuPresenter.SetMenuContext(_menucontext);

            //activate new plugin
            target.Activate();

            target.ContentAreaSurfacePresenter.UpdateLayout();

            _currentPlugin = target;
        }

       


        internal ConsolePlugIn CurrentPlugin
        {
            get
            {
                return this._currentPlugin;
            }
            
        }

        /// <summary>
        /// icon associated with the shell window
        /// </summary>
        public Image Icon
        {
            get
            {
                return _large_icon;
            }
            internal set
            {
                _large_icon = value;
            }
        }

        /// <summary>
        /// Retrieved a messaging pipeline formthe current 
        /// plugin
        /// </summary>
        public PluginMessagingPipeline MessagingPipeline
        {
            get
            {
               
                return _pipeline;
            }
        }

        public LaunchPointApplication RunnableContext
        {
            get { return _startupApp; }
        }        

        /// <summary>
        /// registers the given plugin with the console
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="isactive">inidicates whether the buttong should be set to active style by default.
        /// this value should ALWAYS be true and will be removed from future implementations</param>
        internal void RegisterPlugin(ConsolePlugIn plugin, bool isactive)
        {
            //if the name already exists show a message prompt but do not error out
            if (!_plugins.ContainsKey(plugin.Name))
            {        
                //TODO: remove isactive parameter
                _plugins.Add(plugin.Name, plugin);
                
                //register application
                _surfaceControlPanel.RegisterApplication(plugin, isactive);
            }
            else
            {
                PromptManager.Alert("749BF7A7-7EFD-45c8-8380-E1EC08337263: {0} is already a registered plugin name.", plugin.Name);
            }            
        }

        internal void UnRegisterPlugin(string pluginName)
        {
            if (_plugins.ContainsKey(pluginName))
            {
                //remove from plugin list
                _plugins.Remove(pluginName);
                _surfaceControlPanel.UnRegisterApplication(pluginName);
            }
            else
            {
                PromptManager.Alert("DEFE94C0-4783-4cc7-99F9-8F4C649DD980: {0} is not a registered plugin.", pluginName);
            }
        }

        internal void UnRegisterPlugin(ConsolePlugIn plugin)
        {
            if (_plugins.ContainsKey(plugin.Name))
            {
                //remove from plugin list
                _plugins.Remove(plugin.Name);

                _surfaceControlPanel.UnRegisterApplication(plugin);


            }
            else
            {
                PromptManager.Alert("DEFE94C0-4783-4cc7-99F9-8F4C649DD980: {0} is not a registered plugin.", plugin.Name);
            }
        }

        public void UnloadCurrentPlugin()
        {
            UnRegisterPlugin(this._currentPlugin);
        }

        public void PipelineBroadcastEvent(string application, string filter, string message)
        {

            //TODO:  add peer to peer broadcasting code here
            if (application == null)
            {
                foreach (ConsolePlugIn plugin in _plugins.Values)
                {
                    plugin.RouteMessage(filter, message);
                    
                }                
               // _startupApp.Broadcast(application, filter, message);
            }
            else
            {
                if (_plugins.ContainsKey(application))
                {
                    ConsolePlugIn plugin = _plugins[application];
                    plugin.RouteMessage(filter, message);
                   // _startupApp.Broadcast(application, filter, message);
                }
                else
                {
                    //PromptManager.Alert("78E8A485-6DE6-4301-A001-E3D18DEDE009: The target application for message {0} specified as {1} was not found.",message != null ? message : "",application);
                }
            }

            
        }

      
    }
}